package com.sky.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.sky.properties.AliOssProperties;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

@Data
@AllArgsConstructor
@Slf4j
@Component
public class AliOssUtil {
    @Autowired
    private AliOssProperties aliOssProperties;

//    private String endpoint;
//    private String accessKeyId;
//    private String accessKeySecret;
//    private String bucketName;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    public String upload(MultipartFile file) {
        //获取阿里云oss参数
        String endpoint = aliOssProperties.getEndpoint();
        String accessKeyId = aliOssProperties.getAccessKeyId();
        String accessKeySecret = aliOssProperties.getAccessKeySecret();
        String bucketName = aliOssProperties.getBucketName();

        //获取文件的输入流
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            log.info("文件上传失败：{}",e);
        }

        //利用UUID给上传到oss的对象起个名字，防止重复被覆盖
        String originalFilename = file.getOriginalFilename();
        String objectName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //上传oss
        ossClient.putObject(bucketName,objectName,inputStream);

        //文件访问路径规则 https://BucketName.Endpoint/ObjectName
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder
                .append(bucketName)
                .append(".")
                .append(endpoint)
                .append("/")
                .append(objectName);

        log.info("文件访问URL:{}", stringBuilder.toString());

        return stringBuilder.toString();
    }
}
